import os
import yaml

from oneconvert.datasource.base import BaseDataSource


class YamlDataSource(BaseDataSource):
    def read(self, encoding='utf-8', **kwargs):
        if not os.path.isfile(self.uri):
            raise ValueError(f'the file {self.uri} not found')

        with open(self.uri, 'r', encoding=encoding) as fp:
            return yaml.safe_load(fp)

    def write(self, data, encoding='utf-8', allow_unicode=True, default_flow_style=False, **kwargs):
        dir_name = os.path.dirname(self.uri)
        if dir_name and not os.path.exists(dir_name):
            os.makedirs(dir_name, exist_ok=True)

        with open(self.uri, 'w', encoding=encoding) as fp:
            yaml.dump(data, fp,
                      allow_unicode=allow_unicode,
                      default_flow_style=default_flow_style)
